package com.zhuoyue.common.mqtt.util;

import org.eclipse.paho.client.mqttv3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author wjming
 * @ClassName: MqttUtil
 * @Description: wjming
 * @Date 2021-07-08 16:30
 */
@Component
public class MqttUtil {
    private static MqttClient mqttClient;
    @Value("${mqtt.ip}")
    private String mqttIp;

    public MqttDeliveryToken publish(String topicString, String publication, int qos) {
        MqttDeliveryToken token = null;
        try {
            if (mqttClient == null || !mqttClient.isConnected()) {
                connect();
            }

            // 创建mqtt相关的主题
            // --根据业务需要设置不同的主题
            MqttTopic topic = mqttClient.getTopic(topicString);
            // 创建mqtt消息体
            MqttMessage message = new MqttMessage();

            // 设置消息传输类型
            message.setQos(qos);

            // 设置是否在服务器中保存消息体
            message.setRetained(false);

            // 设置消息的内容
            message.setPayload(publication.getBytes());
            // 发送消息并获取回执
            token = topic.publish(message);

        } catch (Exception e) {
            try {
                disconnect();
            } catch (MqttException e1) {
                System.out.println("程序异常，关闭MQTT连接");
                e1.printStackTrace();
            }
            e.printStackTrace();
        }
        return token;
    }


    private void connect() throws MqttException {

        // 创建MqttClient对象
        mqttClient = new MqttClient(mqttIp, WsMqttServerCommon.CLIENT_ID);

        // 创建一个mqtt的回调类
        WsMqttServerCallBack callback = new WsMqttServerCallBack(
                WsMqttServerCommon.CLIENT_ID);

        // MqttClient绑定
        mqttClient.setCallback(callback);

        // 设置连接选项
        MqttConnectOptions options = new MqttConnectOptions();
        // true:不为客户端保留消息；false:为客户端保留消息
        options.setCleanSession(true);

        // 设置超时时间
        options.setConnectionTimeout(10);
        // 设置会话心跳时间
        options.setKeepAliveInterval(30);

        mqttClient.connect(options);
    }

    private void disconnect() throws MqttException {
        if (mqttClient != null && mqttClient.isConnected()) {
            mqttClient.disconnect(WsMqttServerCommon.QUIESCE_TIMEOUT);
        }
    }
}
